import { useCallback, useEffect, useRef } from 'react'
import * as echarts from 'echarts'

/**
 * 使用Echarts
 * @param options -  绘制echarts的参数
 * @param data -  数据
 */
export const useEcharts = (options: echarts.EChartsCoreOption, data?: unknown) => {
  const echartsRef = useRef<echarts.EChartsType>()
  const htmlDivRef = useRef<HTMLDivElement>(null)

  const dispose = () => {
    if (htmlDivRef.current) {
      echartsRef.current?.dispose()
    }
  }

  const init = useCallback(() => {
    if (options) {
      dispose()
      if (htmlDivRef.current) {
        echartsRef.current = echarts.init(htmlDivRef.current)
        echartsRef.current.setOption(options)
        echartsRef.current?.resize()
      }
    }
  }, [options])

  useEffect(() => {
    if (options) init()
  }, [init, options])

  useEffect(() => {
    init()
    window.addEventListener('resize', init, false)

    return () => {
      window.removeEventListener('resize', init)
      dispose()
    }
  }, [])

  useEffect(() => {
    if (data) {
      echartsRef?.current?.setOption(options)
    }
  }, [data])

  return [htmlDivRef, init] as const
}
